//
//  MainVC.m
//  pyq
//
//  Created by dev-oo on 2017/10/19.
//  Copyright © 2017年 pingmei. All rights reserved.
//

#import "MainVC.h"
#import<WebKit/WebKit.h>
#import "PlayVC.h"
#import "AFURLSessionManager.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>
#import <ShareSDKUI/SSUIShareActionSheetStyle.h>
#import <JavaScriptCore/JavaScriptCore.h>
#import "WXApi.h"


#pragma mark USER_DEFAULTS
#define USER_DEFAULTS_SET(__OBJECT,__KEY) {\
[[NSUserDefaults standardUserDefaults] setObject:__OBJECT forKey:__KEY];\
[[NSUserDefaults standardUserDefaults] synchronize];}

#define USER_DEFAULTS_GET(__KEY) ([[NSUserDefaults standardUserDefaults] objectForKey:__KEY])

@interface MainVC (){
    UIImageView *startIV;
    UIButton *goBtn;
    UIWebView *webView;
    NSURLConnection *theConnection;
    NSString *orderId;
    NSString *courseId;
    NSString *productType;
}
@end

@implementation MainVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
    self.view.backgroundColor = [UIColor colorWithRed:57 green:190 blue:180 alpha:1];
    
    webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    webView.delegate = self;
//    webView.backgroundColor = [UIColor greenColor];
//    [webView loadHTMLString:@"<!DOCTYPE HTML><html lang=\"zh-CN\"><body><p>JavaScriptCore测试页面</p><body><button onclick=\"iosPlayVideo('http://36.111.40.37:17553/Ypq/jbh_yezishu.mp4', '测试的视频哎哎哎哎')\">播放JS按钮</button> <button onclick=\"iosShare('标题', '内容', 'https://www.51ypq.com/cms/uploadFile/image/kaijidaotu.png', 'www.baidu.com')\">分享JS按钮</button>  <button onclick=\"iosWxLogin()\">微信登陆按钮</button> <button onclick=\"iosWxPay('1234','1234','1234','1234','1234','1234','1234')\">微信支付</button> </body></html>" baseURL:nil];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.51ypq.com/"]];
    [webView loadRequest:request];
    [self.view addSubview:webView];
    theConnection= [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
    
    NSString *startImgPath = USER_DEFAULTS_GET(@"startImgPath");
    UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:startImgPath]]];
    startIV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
//    if (img) {
//        startIV.image = img;
//    }else{
        startIV.image = [UIImage imageNamed:@"start"];
//    }
    [self.view addSubview:startIV];
//    [self getStartImg];
    
    goBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    goBtn.frame = CGRectMake((ScreenWidth-80)/2, ScreenHeight-70, 80, 50);
    [goBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    goBtn.titleLabel.font = [UIFont systemFontOfSize:18.0f];
    [goBtn setTitle:@"跳过" forState:UIControlStateNormal];
    [goBtn setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.8]];
    goBtn.layer.masksToBounds = YES;
    goBtn.layer.cornerRadius = 5.0f;
    [goBtn addTarget:self action:@selector(clickGo) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:goBtn];
    
    [self performSelector:@selector(clickGo) withObject:nil afterDelay:6];
    
    
    [UIView beginAnimations:@"FrameAni" context:nil];
    [UIView setAnimationDuration:2.0];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(clickGo)];
    [UIView setAnimationRepeatCount:1];
    [UIView setAnimationDelay:4.0];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    startIV.bounds = CGRectMake(0, 0, ScreenWidth*1.6, ScreenHeight*1.6);
    [UIView commitAnimations];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getWxAccessToken:) name:@"getWxAccessToken" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wxPaySuceess:) name:@"WXPaySuceess" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wxPayFail:) name:@"WXPayFail" object:nil];
    
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    UIButton *btnLoadAgin = [[UIButton alloc]initWithFrame:CGRectMake(0, 20, ScreenWidth, ScreenHeight)];
    [btnLoadAgin setTitle:@"加载失败，点击重试" forState:UIControlStateNormal];
    [btnLoadAgin setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btnLoadAgin addTarget:self action:@selector(clickLoadAgin:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnLoadAgin];
}

-(void)clickLoadAgin:(UIButton *)btn{
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.51ypq.com/"]];
    [webView loadRequest:request];
    [btn removeFromSuperview];
}

-(void)wxPaySuceess:(NSNotification *)notification{
    NSString *payStatus = [notification object];
    NSString *url = [NSString stringWithFormat:@"https://www.51ypq.com/payCallBack?orderId=%@&courseId=%@&productType=%@&payStatus=%@", orderId, courseId, productType, payStatus];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    [webView loadRequest:request];
}

-(void)wxPayFail:(NSNotification *)notification{
    NSString *payStatus = [notification object];
    NSString *url = [NSString stringWithFormat:@"https://www.51ypq.com/payCallBack?orderId=%@&courseId=%@&productType=%@&payStatus=%@", orderId, courseId, productType, payStatus];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    [webView loadRequest:request];
}

-(void)getWxAccessToken:(NSNotification *)notification{
    NSString *code = [notification object];
    NSString *url = [NSString stringWithFormat:@"https://www.51ypq.com/ypq-crm-portal/weixin/redirectUri.ypq?code=%@", code];
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
}

-(void)clickGo{
    startIV.hidden = YES;
    goBtn.hidden = YES;
}

-(void)getStartImg{
    NSString *path = @"https://www.51ypq.com/cms/uploadFile/image/kaijidaotu.png";
    
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    NSURL *URL = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
    [request setHTTPShouldHandleCookies:YES];
    request.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
        
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        NSLog(@"File downloaded to: %@", [filePath absoluteString]);
        USER_DEFAULTS_SET([filePath absoluteString], @"startImgPath");
        UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:filePath]];
        startIV.image = img;
    }];
    [downloadTask resume];
}

-(void)shareTile:(NSString *)title content:(NSString *)content imgUrl:(NSString *)imgUrl url:(NSString *)url{
    //1、创建分享参数
    NSArray* imageArray = @[imgUrl];
//    （注意：图片必须要在Xcode左边目录里面，名称必须要传正确，如果要分享网络图片，可以这样传iamge参数 images:@[@"http://mob.com/Assets/images/logo.png?v=20150320"]）
    if (imageArray) {
        [SSUIShareActionSheetStyle setShareActionSheetStyle:ShareActionSheetStyleSimple];
        NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
        [shareParams SSDKSetupShareParamsByText:content
                                         images:imageArray
                                            url:[NSURL URLWithString:url]
                                          title:title
                                           type:SSDKContentTypeAuto];
        //有的平台要客户端分享需要加此方法，例如微博
        [shareParams SSDKEnableUseClientShare];
        //2、分享（可以弹出我们的分享菜单和编辑界面）
        [ShareSDK showShareActionSheet:nil //要显示菜单的视图, iPad版中此参数作为弹出菜单的参照视图，只有传这个才可以弹出我们的分享菜单，可以传分享的按钮对象或者自己创建小的view 对象，iPhone可以传nil不会影响
                                 items:nil
                           shareParams:shareParams
                   onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                       
                       switch (state) {
                           case SSDKResponseStateSuccess:
                           {
                               UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功"
                                                                                   message:nil
                                                                                  delegate:nil
                                                                         cancelButtonTitle:@"确定"
                                                                         otherButtonTitles:nil];
                               [alertView show];
                               break;
                           }
                           case SSDKResponseStateFail:
                           {
                               UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                               message:[NSString stringWithFormat:@"%@",error]
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"OK"
                                                                     otherButtonTitles:nil, nil];
                               [alert show];
                               break;
                           }
                           default:
                               break;
                       }
                   }
         ];}
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self interfaceOrientation:UIInterfaceOrientationPortrait];
}

-(void)playUrl:(NSString *)videoUrl title:(NSString *)title{
    UINavigationController *nav = self.navigationController;
    PlayVC *playVC = [PlayVC new];
    playVC.videoUrl = videoUrl;
    playVC.videoTitle = title;
    [nav pushViewController:playVC animated:YES];
}

/**
 *  强制屏幕转屏
 *
 *  @param orientation 屏幕方向
 */
- (void)interfaceOrientation:(UIInterfaceOrientation)orientation{
    // arc下
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        SEL selector = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        int val = orientation;
        // 从2开始是因为0 1 两个参数已经被selector和target占用
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];
    }
    // 直接调用这个方法通不过apple上架审核
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIInterfaceOrientationLandscapeRight] forKey:@"orientation"];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    __weak MainVC *weakSelf = self;
    JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    context[@"iosPlayVideo"] = ^{
        NSArray *arg = [JSContext currentArguments];
        for (id obj in arg) {
            NSLog(@"%@", obj);
        }
        NSString *arg0 = [NSString stringWithFormat:@"%@", [arg objectAtIndex:0]];
        NSString *arg1 = [NSString stringWithFormat:@"%@", [arg objectAtIndex:1]];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf playUrl:arg0 title:arg1];
        });
    };
    
    context[@"iosShare"] = ^{
        NSArray *arg = [JSContext currentArguments];
        for (id obj in arg) {
            NSLog(@"iosShare %@", obj);
        }
        NSString *arg0 = [NSString stringWithFormat:@"%@", [arg objectAtIndex:0]];
        NSString *arg1 = [NSString stringWithFormat:@"%@", [arg objectAtIndex:1]];
        NSString *arg2 = [NSString stringWithFormat:@"%@", [arg objectAtIndex:2]];
        NSString *arg3 = [NSString stringWithFormat:@"%@", [arg objectAtIndex:3]];
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf shareTile:arg0 content:arg1 imgUrl:arg2 url:arg3];
        });
    };
    
    context[@"iosWxLogin"] = ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf loginWx];
        });
    };
    
    context[@"iosWxPay"] = ^{
        NSLog(@"%@", @"iosWxPay11");
        NSArray *arg = [JSContext currentArguments];
        for (id obj in arg) {
            NSLog(@"%@", obj);
        }
        NSString *appid = [NSString stringWithFormat:@"%@", [arg objectAtIndex:0]];
        NSString *partnerid = [NSString stringWithFormat:@"%@", [arg objectAtIndex:1]];
        NSString *prepayid = [NSString stringWithFormat:@"%@", [arg objectAtIndex:2]];
        NSString *package = [NSString stringWithFormat:@"%@", [arg objectAtIndex:3]];
        NSString *noncestr = [NSString stringWithFormat:@"%@", [arg objectAtIndex:4]];
        NSString *timeStr = [NSString stringWithFormat:@"%@", [arg objectAtIndex:5]];
        NSNumber *timestamp = [NSNumber numberWithLong:[timeStr longLongValue]];
        NSString *sign = [NSString stringWithFormat:@"%@", [arg objectAtIndex:6]];
        orderId = [NSString stringWithFormat:@"%@", [arg objectAtIndex:7]];
        courseId = [NSString stringWithFormat:@"%@", [arg objectAtIndex:8]];
        productType = [NSString stringWithFormat:@"%@", [arg objectAtIndex:9]];
        dispatch_async(dispatch_get_main_queue(), ^{
            PayReq *request = [[PayReq alloc] init];
            request.partnerId = partnerid;
            request.prepayId= prepayid;
            request.package = package;
            request.nonceStr= noncestr;
            NSNumber *ts = timestamp;
            request.timeStamp = (UInt32) ts.longValue;
            request.sign= sign;
            [WXApi sendReq:request];
        });
    };
}

-(void)loginWx{
    if ([WXApi isWXAppInstalled]) {
        SendAuthReq *req = [[SendAuthReq alloc] init];
        req.scope = @"snsapi_userinfo";
        req.state = @"App";
        [WXApi sendReq:req];
    } else {
        [self setupAlertController];
    }
}

#pragma mark - 设置弹出提示语
- (void)setupAlertController {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请先安装微信客户端" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *actionConfirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:actionConfirm];
    [self presentViewController:alert animated:YES completion:nil];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"getWxAccessToken" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"WXPaySuceess" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"WXPayFail" object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; 
}

@end






